package com.yu.yupicture.manger.upload;

import cn.hutool.core.io.FileUtil;
import com.yu.yupicture.Untils.ThrowUntil;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * 处理通过文件上传
 */
@Slf4j
@Service
public class FileUntil extends CommenUpliadUntil {

    @Value("${file.image.extensions}")
    private List<String> imageExtensions;

    /**
     * 校验文件
     * @param input
     */
    @Override
    public void validateFile(Object input) {
        MultipartFile multipartFile = (MultipartFile) input;
        //1：校验参数
        ThrowUntil.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        //2：校验文件类型
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        if (!imageExtensions.contains(suffix)) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }
        //3：校验文件大小
        if (multipartFile.getSize() > 6 * 1024 * 1024) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过6MB");
        }
    }

    /**
     * 获取原始文件名
     * @param input
     * @return
     */
    @Override
    public String getFileName(Object input) {
        MultipartFile multipartFile = (MultipartFile) input;
        ThrowUntil.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        return multipartFile.getOriginalFilename();
    }

    /**
     * 处理文件来源
     * @param input
     * @param file
     */
    @Override
    public void createTempFile(Object input, File file) {
        MultipartFile multipartFile = (MultipartFile) input;
        ThrowUntil.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            log.error("file upload error", e);
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "文件上传失败");
        }
    }
}
